package org.net5ijy.security.validate;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.net5ijy.security.config.security.SecurityConfig;
import org.net5ijy.security.util.ApplicationSourceUtil;
import org.net5ijy.security.util.ResponseMessage;
import org.net5ijy.security.util.ValidateCodeUtil;
import org.net5ijy.security.util.exception.ValidateCodeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

/**
 * SmsValidateCodeGenerator
 *
 * @author XGF
 * @date 2020/11/30 22:22
 */
@Component("smsValidateCodeGenerator")
public class SmsValidateCodeGenerator implements ValidateCodeGenerator,
    InitializingBean {

  private static Logger log = LoggerFactory
      .getLogger(SmsValidateCodeGenerator.class);

  public static final String SMS_VALIDATE_CODE_SESSION_KEY = "smsValidateCode";

  public static final String MOBILE_REGEX = "^1[0-9]{10}$";

  public static final String MOBILE_PARAMETER_NAME = "mobile";

  // 有效期为60秒
  private int expireIn = 60000;

  private int length = 4;

  @Override
  public ValidateCode generateValidateCode(HttpServletRequest request,
      HttpServletResponse response) throws IOException {
    // 手机号码
    String mobile = request.getParameter(MOBILE_PARAMETER_NAME);
    // 手机号验证
    if (mobile == null || !mobile.matches(MOBILE_REGEX)) {
      throw new ValidateCodeException("手机号不合理: " + mobile);
    }
    // 生成随机字符串
    String codeStr = ValidateCodeUtil.createValidateCode(length);
    // 创建验证码对象
    SmsValidateCode code = new SmsValidateCode(mobile, codeStr, expireIn);
    // 把验证码放到session里面
    request.getSession().setAttribute(SMS_VALIDATE_CODE_SESSION_KEY, code);
    return code;
  }

  @Override
  public void sendValidateCode(ValidateCode code, HttpServletRequest request,
      HttpServletResponse response) throws IOException {

    SmsValidateCode smsCode = (SmsValidateCode) code;
    log.info("[{}]已发送短信验证码[{}]", smsCode.getMobile(), smsCode.getCode());
    // 返回成功消息
    ResponseMessage msg = ResponseMessage.success();
    msg.setMessage("发送成功[" + smsCode.getCode() + "]");
    String json = SecurityConfig.toJson(msg);
    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
    response.getWriter().print(json);
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    ApplicationSourceUtil util = ApplicationSourceUtil
        .getApplicationSourceUtil();
    this.expireIn =
        util.getInteger("net5ijy.security.smsCode.expireIn", this.expireIn);
    this.length =
        util.getInteger("net5ijy.security.smsCode.length", this.length);
  }
}
